package com.schedule.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.schedule.mapper.*;
import com.schedule.pojo.*;
import com.schedule.service.IAdminRoleService;
import com.schedule.service.IPlayerService;
import com.schedule.tools.IDExamine;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RestController;

import com.schedule.controller.examine.PlayerJudge;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = "参赛者管理")        //swagger2对该接口的一个描述，实际的扫描路径已经写在Swagger2的配置类里面了
@Slf4j
@RestController
public class PlayerController {

    @Autowired
    private JdbcTemplate jdbcTemplate;            //JdbcTemplate类是spring对JDBC的封装

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private PlayerMapper playerMapper;            //选手信息mapper,这里的“无法自动装配”报错不影响使用

    @Autowired
    private SignFormMapper signFormMapper;

    @Autowired
    private CompetitionMapper competitionMapper;

    @Autowired
    private IAdminRoleService adminRoleService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private IPlayerService playerService;

    private CompetitionController competitionController;

    private IDExamine idExamine=new IDExamine();

    //检查用户输入信息的正确性的类
    public PlayerJudge playerJudge=new PlayerJudge();

    @ApiOperation(value = "获取所有选手信息")         //value的值用于说明该接口的作用
    @ResponseBody
    @GetMapping(value = "/getPlayer")
//    Map 是一个键值对，前面的String类型为属性名，后面的为对应的值
    public RespBean PlayerGet(){
        log.info("方法开始运行");
        String sql="select * from t_player";
        List<Map<String,Object>> PlayerList=jdbcTemplate.queryForList(sql);
        int num=playerMapper.selectList(null).size();
        return RespBean.success("查询到"+num+"个选手",PlayerList);
    }

    @ApiOperation("报名信息注册")
    @PostMapping("/playLogin")
    //与表单的input标签的name属性值一样时就会自动获取到输入的值
    public RespBean PlayerLogin(@RequestBody Player newPlayer){
        //将当前用户信息和填写的选手信息绑定，并使用当前用户的电话号码，防止一个电话号码对应多个选手信息
        System.out.println("the player is "+newPlayer);
        newPlayer.setPId(0);

        Admin admin=(Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int Aid=admin.getId();
        System.out.println("aid is "+Aid);
        newPlayer.setAid(Aid);
        newPlayer.setTelephone(admin.getPhoneNum());
      //  String Info=playerJudge.Examine(newPlayer);

        log.info("信息为："+newPlayer);
        //判断前段提供的信息是否满足格式
//        if(!"输入的年龄和身份证号上的年龄信息不符，已自动修改\n".equals(Info) && (!"".equals(Info) || Info.length()!=0)){
//            return RespBean.error("注册失败");
//        }
        if(newPlayer.getAge()<6 || newPlayer.getAge()>22){
            return RespBean.error("年龄不适合报名该比赛");
        }
        int N=playerMapper.insert(newPlayer);
        log.info(N+"个选手注册成功");

        //建立用户和权限的关系表，当前默认为运动员
//        Role role=roleMapper.selectOne(new QueryWrapper<Role>().eq("nameZh","运动员"));
//        AdminRole adminRole=new AdminRole();
//        adminRole.setAdminId(Aid);
//        adminRole.setRid(role.getId());
//        boolean saveSuccess=adminRoleService.save(adminRole);
//        if(!saveSuccess) return RespBean.error("权限信息绑定失败");

        return RespBean.success("注册成功",newPlayer);
    }


    @PostMapping("getNowUserInfo")
    @ApiOperation("获取当前登录用户的选手信息")
    public RespBean getUserInfos(){
        Admin admin=(Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int Aid=admin.getId();

        Player nowPlayer=playerMapper.selectOne(new QueryWrapper<Player>().eq("Aid",Aid));
        if(nowPlayer!=null) return RespBean.success("查询成功",nowPlayer);
        return RespBean.error("当前用户没有对应的选手信息");
    }

    @ApiOperation("删除参赛者信息")
    @GetMapping("/playerDelete")
    public RespBean PlayerDelete(int i){
        int Num=playerMapper.deleteById(i);
        if(Num==0){
            return RespBean.error("没有对应选手信息，删除失败");
        }

        jdbcTemplate.execute("ALTER TABLE t_player AUTO_INCREMENT =1");        //每次删除后都执行这段sql语句，可以让在删除数据后依然接着删除的数据主键增长

        return RespBean.success("删除成功");
    }

    @ApiOperation("修改参赛者信息")
    @PostMapping("/playerUpdate")
    public RespBean playerUpdate(@RequestParam("school") String school){
        Player AlteredPlayer=(Player) getUserInfos().getObj();
        AlteredPlayer.setSchool(school);

        //更新选手的年龄
        int age=idExamine.getYear(AlteredPlayer.getID_Number());
        AlteredPlayer.setAge(age);

        int Num=playerMapper.updateById(AlteredPlayer);
        if(Num!=0)  return RespBean.success(Num+"个选手的信息已经修改",AlteredPlayer);
        return RespBean.error("当前数据库不存在该选手信息，修改失败");
    }

    //获取选手可以报名的比赛限制
    @ApiOperation("获取参赛者能够参加的比赛")
    @PostMapping("/ableAttendCom")
    public RespBean ableAttened(int PId){
        Player player=playerMapper.selectById(PId);
        String ableCompetition="";

        if(!player.getSex()) ableCompetition+="男子";
        else ableCompetition+="女子";

        int age=player.getAge();
        if(age>=6 && age<12) ableCompetition+="小学组";
        else if(age>=12 && age<15) ableCompetition+="初中组";
        else if(age>=15 && age<18) ableCompetition+="高中组";
        else if(age>=18 && age<=22) ableCompetition+="高校组";
        else RespBean.error("没有可以报名的比赛");

        return RespBean.error(ableCompetition);
    }

    //已经报名了的比赛数量
    @PostMapping("/getSportNum")
    @ApiOperation("获取选手已经报名的比赛数量")
    public int getSportNum(@RequestParam("Pid") Integer Pid){
        int PId=Pid.intValue();
        int LognedNum=gradeMapper.selectList(new QueryWrapper<Grade>().eq("PId",PId)).size();
        return LognedNum;
    }

    //报名函数
    @PostMapping("/registration/entry/attend")
    @ApiOperation("报名某项比赛")
    public RespBean attendCom(@RequestBody Sign sign){
        int LognedNum=getSportNum(sign.getPID());
        if(LognedNum>=2) return RespBean.error("已达到报名数量极限值2项！");

        //判断选手是否可以报名该比赛
        String limit=ableAttened(sign.getPID()).getMessage();
        if(!sign.getCName().endsWith(limit)) return RespBean.error("报名失败，不满足报名条件");

        //判断通过之后进行报名
        int num=signFormMapper.insert(sign);
        if(num==0) return RespBean.error("报名失败");
        return RespBean.success("报名成功",sign);
    }

    @PostMapping("getAllAttendInfo")
    @ApiOperation("获取所有报名信息")
    public RespBean getAllAttendInfo(){
        List<SignInfo> signInfoList=gradeMapper.selectJoinList(SignInfo.class,
                new MPJLambdaWrapper<Grade>()
                        .select(Grade::getCName,Grade::getPId,Grade::getComment)
                        .selectAs(Player::getName,SignInfo::getPName)
                        .leftJoin(Player.class,Player::getPId,Grade::getPId));
        if(signInfoList.size()!=0){
            return RespBean.success("查询成功",signInfoList);
        }
        return RespBean.error("没有数据，请先写入数据");
    }

    @PostMapping("getAttendInfo_Page")
    @ApiOperation("分页查询报名信息")
    public RespBean getAttendInfosPage(@RequestParam("PageNum") int PageNum){
        Page<SignInfo> signInfoPage=new Page<>(PageNum,5);
        IPage<SignInfo> signIPage=gradeMapper.selectJoinPage(signInfoPage,SignInfo.class,
                new MPJLambdaWrapper<Grade>()
                        .selectAll(Grade.class)
                        .selectAs(Player::getName,SignInfo::getPName)
                        .leftJoin(Player.class,Player::getPId,Grade::getPId));
        List<SignInfo> signInfos=signInfoPage.getRecords();
        long PNum=signInfoPage.getPages();
        long Total=signInfoPage.getTotal();
        if(signInfos.size()!=0) return RespBean.success(Total+"-"+PNum,signInfos);
        return RespBean.error("没有查询到对应页的信息");
    }

    @PostMapping("/getSignInfo")
    @ApiOperation("获取参赛者的报名信息")
    public RespBean getSignInfo(@RequestParam("Pid") Integer Pid){
        int PId=Pid.intValue();
        List<SignInfo> signInfos= gradeMapper.selectJoinList(SignInfo.class,
                new MPJLambdaWrapper<Grade>()
                        .select(Grade::getCName,Grade::getPId)
                        .selectAs(Player::getName,SignInfo::getPName)
                        //连表查询条件，两个参数相等
                        .leftJoin(Player.class,Player::getPId,Grade::getPId)
                        //查询条件
                        .eq(Grade::getPId,PId));
        if(signInfos.size()!=0) return RespBean.success("查询成功",signInfos);
        else return RespBean.error("没有查询到相关报名信息");
    }

    @PostMapping("/registration/manage/delSignInfo")
    @ApiOperation("取消报名")
    public RespBean delSignInfo(@RequestParam("PId") int PId,@RequestParam("CName") String CName){
        System.out.println("Cname是"+CName);
        //获取当前用户的Aid
        Admin admin=(Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int Aid=admin.getId();
        //获取当前用户的PId
        Player nowPlayer=playerMapper.selectOne(new QueryWrapper<Player>().eq("Aid",Aid));

        List<AdminRole> adminRoles=adminRoleMapper.selectList(new QueryWrapper<AdminRole>().eq("adminId",Aid));
        if(adminRoles.size()==0) return RespBean.error("没有权限");
        //当当前用户是运动员时，没有权限修改其他人的报名信息
        if (adminRoles.get(0).getRid()==2 && PId!=nowPlayer.getPId()) return RespBean.error("你没有权限操作其他人的报名信息");

        int num=signFormMapper.delete(new QueryWrapper<Sign>().eq("PId",PId).eq("CName",CName));
        if(num!=0) return RespBean.success("删除成功");
        return RespBean.error("删除失败");
    }

}
